package net.suncaper.demo.controller;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import net.suncaper.demo.domain.User;
import net.suncaper.demo.service.UserService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/register")
    public String registerPage() {
        return "pages/home/register.html";
    }

    @PostMapping("/register")
    public String saveUser(User user, String passwordRepeat, HttpServletResponse resp) throws IOException {
        if (!userService.selectUserByEmail(user.getUserEmail()).isEmpty()) {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.print("<script>alert('The email has been registered ');  </script>");
            out.flush();
            return "pages/home/register";
        } else {
            if (user.getUserPassword().equals(passwordRepeat)) {
                userService.saveUser(user);
                return "redirect:/user/login";
            } else {
                resp.setCharacterEncoding("UTF-8");
                PrintWriter out = resp.getWriter();
                out.print("<script>alert('输入密码与确认密码不一致，请重新输入 ');  </script>");
                out.flush();
                return "pages/home/register";
            }
        }
    }

    @RequestMapping("/login")
    public String loginPage() {
        return "pages/home/login.html";
    }

    @PostMapping("/login")
    public String login(User user, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if (!userService.selectUserByEmail(user.getUserEmail()).isEmpty()) {
            User findUser = userService.selectUserByEmail(user.getUserEmail()).get(0);
            String password = findUser.getUserPassword();
            if (password.equals(user.getUserPassword())) {
                HttpSession session = req.getSession();
                session.setAttribute("user", findUser);
//                resp.setCharacterEncoding("utf-8");
//                PrintWriter out = resp.getWriter();
//                out.print("<script>alert('successed ');  </script>");
//                out.flush();


//            return "redirect:/user/homepage";
             return "pages/home/home.html";
            } else {
                resp.setCharacterEncoding("UTF-8");
                PrintWriter out = resp.getWriter();
                out.print("<script>alert('password wrong');  </script>");
                out.flush();

                return "pages/home/login";

            }
        } else {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.print("<script>alert('no email ');  </script>");
            out.flush();
            return "pages/home/login";
        }

    }

    @RequestMapping("/homepage")
    public String mainPage() {
        return "pages/home/home.html";
    }

    @RequestMapping("/userpage")
    public String userPage() {
        return "pages/user/index.html";
    }

    @RequestMapping("/userinfo")
    public String userInfoPage() {
        return "pages/user/information.html";
    }

    @PostMapping("/userinfo")
    public String saveUserInfoPage(User user, HttpServletRequest req, String passwordRepeat, HttpServletResponse resp) throws IOException {
        if (!user.getUserPassword().equals(passwordRepeat)) {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.print("<script>alert('输入密码与确认密码不一致，请重新输入 ');  </script>");
            out.flush();
            return "pages/user/information.html";
        } else {
            HttpSession session = req.getSession();
            User findUser = (User) session.getAttribute("user");
            user.setUserType(findUser.getUserType());
            user.setUserCreatetime(findUser.getUserCreatetime());
            int id = findUser.getUserId();
            userService.updateUserInfo(user, id);
            return "redirect:/user/login";
        }
    }

    @RequestMapping("/findPassword")
    public String findPasswordPage() {
        return "pages/user/question.html";
    }

    @PostMapping("/findPassword")
    public String findPassword(String email, HttpServletResponse resp) throws IOException, MessagingException {
        if (!userService.selectUserByEmail(email).isEmpty()) {
            User user = userService.selectUserByEmail(email).get(0);
            //重新设置密码
            String password = user.getUserName() + (int) (Math.random() * 10000);
            user.setUserPassword(password);
            userService.updateUserInfo(user, user.getUserId());
            // 设置邮件

            // 收件人电子邮箱
            String to = user.getUserEmail();

            // 发件人电子邮箱
            String from = "340350401@qq.com";

            // 指定发送邮件的主机为 smtp.qq.com
            String host = "smtp.qq.com";  //QQ 邮件服务器

            // 获取系统属性
            Properties properties = System.getProperties();

            // 设置邮件服务器
            properties.setProperty("mail.smtp.host", host);

            properties.put("mail.smtp.auth", "true");
            // 获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("340350401@qq.com", "wsqtvzebggcabggf"); //发件人邮件用户名、授权码
                }
            });


            Message msg = new MimeMessage(session);
            msg.setSubject("找回密码通知");// 设置邮件主题


            msg.setFrom(new InternetAddress("340350401@qq.com"));// 设置邮件来源
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(user.getUserEmail()));

            String msgContent = "亲爱的会员" + user.getUserName() + "，您好，<br/><br/>"

                    + "您在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "提交找回密码的请求。<br/><br/>"

                    + "以下是您的帐户及密码信息：<br/><br/>"

                    + "用户名：" + user.getUserName() + "，密码：" + password + "<br/><br/>"

                    + "该密码是临时密码，请您尽快修改密码，感谢使用本系统。" + "<br/><br/>"

                    + "此为自动发送邮件，请勿直接回复！";

            msg.setContent(msgContent, "text/html;charset=utf-8");// 设置邮件内容，为html格式

            // 发送邮件

            Transport.send(msg);

            return "redirect:/user/passwordSuccess";
        } else {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.print("<script>alert('该邮箱不存在，请检查后重新输入');  </script>");
            out.flush();
            return "pages/question.html";
        }
    }
    @RequestMapping("/passwordSuccess")
    public String passwordSuccess()
    {
     return"pages/user/passwordSuccess.html";
    }

    @RequestMapping("/payPage")
    public  String payPage(){
        return"pages/home/pay.html";
    }

    @RequestMapping("/paySuccess")
    public  String paySuccess(){
        return"pages/home/paySuccess.html";
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        return "redirect:/user/homepage";

    }
}

